import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '../views/login'
import layout from '../views/layout'
import { getToken } from '../utile/token'
import user from '../views/layout/user'
import chart from '../views/layout/chart'
import enterprise from '../views/layout/enterprise'
import question from '../views/layout/question'
import subject from '../views/layout/subject'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/layout',
    name: 'layout',
    component: layout,
    children: [
      {
        path: 'user',
        name: 'user',
        component: user
      },
      {
        path: 'enterprise',
        name: 'enterprise',
        component: enterprise
      },
      {
        path: 'chart',
        name: 'chart',
        component: chart
      },
      {
        path: 'question',
        name: 'question',
        component: question
      },
      {
        path: 'subject',
        name: 'subject',
        component: subject
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 解决路由重复报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
/**
 * beforeEach 导航守卫
 *
 * to 去往何处
 * from 从何而来
 * next 控制去不去或者去到哪里，并且必须要要调用，否则就会一直卡在这儿
 *  next() 如果里面不加任何参数，就是正常的跳转到下一个页面
 *  next 如果里面加了参数，就是跳转到指定的页面
 */
// 访问的白名单，可以直接通行
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  // 访问的路径在白名单中
  if (whiteList.includes(to.path)) {
    next()
  } else {
    if (getToken()) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
